package com.cssw.fyzb.core.es;

import org.elasticsearch.common.transport.TransportAddress;

import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Feng Chen
 */
public abstract class TransportAddressSupport {

    private TransportAddressSupport() {

    }

    public static List<TransportAddress> getAddrs(String addrs) {
        List<TransportAddress> addrList = new ArrayList<TransportAddress>();
        for (Addr addr : AddrProvider.getAddrs(addrs)) {
            addrList.add(new TransportAddress(new InetSocketAddress(addr.getHost(), addr.getPort())));
        }
        return addrList;
    }


    private static class Addr {

        private String host;

        private int port;

        public Addr(String host, int port) {
            this.host = host;
            this.port = port;
        }

        public String getHost() {
            return host;
        }

        public void setHost(String host) {
            this.host = host;
        }

        public int getPort() {
            return port;
        }

        public void setPort(int port) {
            this.port = port;
        }

    }


    private abstract static class AddrProvider {

        private final static String ADDR_SPLIT = ";|,";

        private AddrProvider() {

        }

        public static List<Addr> getAddrs(String addrs) {
            List<Addr> res = new ArrayList<Addr>();
            String[] _addrs = addrs.split(ADDR_SPLIT);
            for (String addr : _addrs) {
                res.add(AddrParser.parse(addr));
            }
            return res;
        }

    }


    // 地址解析器
    private abstract static class AddrParser {

        private final static String PORT_SPLIT = ":";

        private AddrParser() {

        }

        public static Addr parse(String addr) {
            String[] _addr = addr.split(PORT_SPLIT);
            return new Addr(_addr[0], Integer.parseInt(_addr[1]));
        }

    }


}
